use strict;
use warnings;

use GSEA::Config::ProjectConfig;

use GSEA::FileReading::FileReader;

use GSEA::ES::EScalculator; 

use GSEA::Chart::ChartCreator; 

use GSEA::Pvalue::PvalueCalculator;
use GSEA::Pvalue::PvalueSearcher;
use GSEA::Pvalue::Permutor;

use GSEA::FDR::ScoreNormalizer ; 
use GSEA::FDR::FdrCleaner ;

#############    configuration values     ##############
my $graphoutPath	= ".\\graphout\\graphout.exe";
my $DBfile			= ".\\fichier.csv" ;
my $width 			= 800	;
my $height			= 800	;
my $cpp_version		= 1		;
my $Npermutations	= 1000	;
########################################################


#use geneGenerator ;
#my $gg = geneGenerator->constrGeneGenerator( 100 , "file1.txt" , 10, "file2.txt" );
#$gg->generateFiles();



# STEP 1 :  reading the project configuration file
my $projectConfig = GSEA::Config::ProjectConfig->constrProjectConfig("projet.txt");









# STEP 2 :  reading the genesets files 
my $fileReader = GSEA::FileReading::FileReader->constrFileReader("","");
my @L_table ;
my @S_table ;

$fileReader->set_Lfile( $projectConfig->getLFilePath() ) ;
@L_table = $fileReader->read_Lfile() ;

my @sfiles = $projectConfig->getSFilePath();
for( my $i= 0 ; $i< @sfiles ; $i++ )
{
	$fileReader->set_Sfile( $sfiles[$i] ) ;
	my @temp =  split( /\\/ , $sfiles[$i]) ;my $name = $temp[ $#temp ];
	
	
	my @table = $fileReader->read_Sfile() ;
	
	my @info = ( $name , \ @table ) ;
	push( @S_table , \@info );
}






my @resultTable ;

# STEP 3 : loop on each Stable , scores computing
for( my $i= 0 ; $i< @S_table ; $i++ )
{
	my @S_tableInfo	= @{ $S_table[$i] } ;
	my @table 		= @{ $S_tableInfo[1] } ; 
	my $name 		= $S_tableInfo[0] ;
	
	print("\n  ---- S_table No $i : $name ---- \n");
	
	
	#building the Enrichment Score calculator
	my $EScalculator = GSEA::ES::EScalculator->constrEScalculator( \ @L_table , \ @table , $projectConfig->getPparameter() );
	
	# searching genes in common in the 2 sets
	$EScalculator->searchCommonGenes();
	
	# checking if the ratio of common genes is OK
	my ( $Nmiss , $Nhit ) = $EScalculator->getHitMiss() ;
	my $ratio = $Nhit /  ($#table+1);
	
	print("\nratio = $ratio");
		
	if( $ratio >= $projectConfig->getTparameter() )
	{
		$EScalculator->CalculateEScourb();
	
		my @courb	= $EScalculator->getCourb()			;
		my @distrib	= $EScalculator->getDistribution()	;
		( my $ESmin , my $ESmax ) = $EScalculator->getScores() ;
			
		my @info = ( $name , $ESmin ,   $ESmax , $Nmiss , $Nhit , \@courb , \@distrib ) ;
		push( @resultTable , \ @info  );
	}
	#else{ print("insufficient ratio:)"); }
}

	
	
	
	
	
	
	
	
	
	
# STEP 4 : 2 different process if there is 1 or several S_file's
if( @resultTable == 1 )
{
	( my $name , my $ESmin ,  my $ESmax , my $Nmiss ,  my $Nhit ,my $pt_courb ,my $pt_distrib ) = @{ $resultTable[0] };
	
	my $pvalue = -1;
	
	my $score = $ESmax ;if( abs($ESmin)>$ESmax   ){ $score = $ESmin ; }
 	 
	
	print("\n[1 seul resultat  $name ] esmin=$ESmin ,  esmax=$ESmax , nmiss=$Nmiss ,  nhit=$Nhit , score=$score");
	
	# P-value computation : 2 methods , depending on the 'p' parameter
	if( $projectConfig->getPparameter() == 0 )
	{
		
		my $pvs = GSEA::Pvalue::PvalueSearcher->constrPvalueSearcher( $DBfile , $width , $height  , $score  ) ;
	 	my $val = $pvs->compute() ;
	 	if( !$val)
	 	{ 
			
			if( ! $cpp_version )
			{	 
				my $pvc = GSEA::Pvalue::PvalueCalculator->constrPvalueCalculator( $Nhit ,  $Nmiss , $score ) ;
				$pvalue = $pvc->compute() ;
				print("\npvalue=$pvalue");
			}
			else
			{
				system("pvalue $Nhit $Nmiss $score 10 out.txt");
				if( ! open(EXISTFILE , "<out.txt") ) { die("huh.. error happened while trying to open the file ! $! "); }
			
				my $line = ""; 
				while(<EXISTFILE>)
				{
					$line = $_ ; 
					chomp($line);
					print("\npvalue>$line\n");
				}
				
				close(EXISTFILE);
				
				$pvalue = $line ;
			}
	 	}else{ $pvalue = 0 ; }
		
	}
	else
	{
		my $permutor = GSEA::Pvalue::Permutor->constrPermutor( $Nhit , \ @L_table  , $Npermutations, $projectConfig->getPparameter());
		$pvalue = $permutor->computePvalue($score);
		print("\npvalue>$pvalue\n");
	}
	
	
	# drawing the charts :
	my $chartCreator = GSEA::Chart::ChartCreator->constrChartCreator($graphoutPath , $width , $height );
		
	$chartCreator->drawEScourb( ".\\EScourb_".$name , $pt_courb ) ;
	$chartCreator->drawGeneSetDistribution( ".\\ScoreDistrib_".$name , $pt_distrib ) ;
	
	
	
	# writing score and pvalue in a file
	my $scoreFile = $name."_score_pvalue.txt" ;
	if( ! open(LOGFILE , ">$scoreFile") ) { die("huh.. error happened ! $! "); } 
	print( LOGFILE   $score."\n" ) ;
	print( LOGFILE   $pvalue."\n" ) ;
	close( LOGFILE );
	
}
else
{
	my @NormResultTable ;
	for( my $i= 0 ; $i< @resultTable ; $i++ )
	{
		( my $name , my $ESmin ,  my $ESmax , my $Nmiss ,  my $Nhit ,my $pt_courb ,my $pt_distrib ) = @{ $resultTable[$i] };
			
		my $score = $ESmax ;
		if( abs($ESmin)>$ESmax   ){ $score = $ESmin ; }
		
		print("\n[resultat  $name ] esmin=$ESmin ,  esmax=$ESmax , nmiss=$Nmiss ,  nhit=$Nhit , score=$score");
		
		my $normalizer = GSEA::FDR::ScoreNormalizer->constrScoreNormalizer( $Nhit ,  \ @L_table , $Npermutations , $projectConfig->getPparameter() );
		( my $NES , my $NPvalue ) = $normalizer->normalizeScore($score);
		print("\n nes=$NES  npvalue=$NPvalue \n");
		
		my @info = ( $name , $score , $NPvalue, $pt_courb ,$pt_distrib  ) ;
		push( @NormResultTable , \ @info  );
				
	}
	
	my $FDRcleaner = GSEA::FDR::FdrCleaner->constrFdrCleaner(  \ @NormResultTable ,  $projectConfig->getAlphaparameter() );
	@NormResultTable = $FDRcleaner->clean() ;
	
	
	# writing score and pvalue in files
	for( my $i= 0 ; $i< @NormResultTable ; $i++ )
	{
		my ( $name , $score , $NPvalue , $pt_courb , $pt_distrib) = @{ $NormResultTable[$i] } ;


		# drawing the charts :
		my $chartCreator = GSEA::Chart::ChartCreator->constrChartCreator($graphoutPath , $width , $height );
		
		$chartCreator->drawEScourb( ".\\EScourb_".$name , $pt_courb ) ;
		$chartCreator->drawGeneSetDistribution( ".\\ScoreDistrib_".$name , $pt_distrib ) ;



		my $scoreFile = $name."_score_pvalue.txt" ;
		print("\ncreate file = ".$scoreFile);
		
		if( ! open(LOGFILE , ">$scoreFile") ) { die("huh.. error happened ! $! "); } 
		print( LOGFILE   $score."\n" ) ;
		print( LOGFILE   $NPvalue."\n" ) ;
		close( LOGFILE );
	}
}

